import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class SharedPrefUtil {
  late SharedPreferences _prefs;
  static final SharedPrefUtil _instance = SharedPrefUtil._internal();

  factory SharedPrefUtil() {
    return _instance;
  }

  SharedPrefUtil._internal();

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  Future<void> setData(String key, dynamic value) async {
    // ignore: unnecessary_null_comparison
    if (_prefs == null) {
      throw Exception("SharedPreferences has not been initialized.");
    }

    if (value is String) {
      await _prefs.setString(key, value);
    } else if (value is int) {
      await _prefs.setInt(key, value);
    } else if (value is double) {
      await _prefs.setDouble(key, value);
    } else if (value is bool) {
      await _prefs.setBool(key, value);
    } else if (value is List<String>) {
      await _prefs.setStringList(key, value);
    } else {
      throw Exception("Unsupported data type");
    }
  }

  dynamic getData(String key) {
    // ignore: unnecessary_null_comparison
    if (_prefs == null) {
      throw Exception("SharedPreferences has not been initialized.");
    }
    return _prefs.get(key);
  }

  Future<void> removeData(String key) async {
    // ignore: unnecessary_null_comparison
    if (_prefs == null) {
      throw Exception("SharedPreferences has not been initialized.");
    }
    await _prefs.remove(key);
  }

  // 保存 JSON 数据
  Future<void> setJsonData(String key, Map<String, dynamic> jsonData) async {
    final jsonString = json.encode(jsonData);
    await setData(key, jsonString);
  }

  // 读取 JSON 数据
  Map<String, dynamic> getJsonData(String key) {
    final jsonString = getData(key);
    if (jsonString != null) {
      return json.decode(jsonString);
    }
    return {};
  }

  /// 获取持久化数据中是否包含某个key
  bool containsKey(String key) {
    return _prefs.containsKey(key);
  }

  /// 清除所有缓存
  Future<void> clearAllData() async {
    // ignore: unnecessary_null_comparison
    if (_prefs == null) {
      throw Exception("SharedPreferences has not been initialized.");
    }
    await _prefs.clear();
  }
}

//本地存储key
class SharedKey {
  static String strThemeKey = "strThemeKey"; //Theme样式
  static String strModeKey = "strModeKey"; //System Mode  / Dark Mode
  static String strLangKey = "strLangKey"; //语言
  static String strGuideKey = "strGuideKey"; //引导页

  static String strCartListKey = "strCartListKey"; //cart list
  static String strRemember = "strRemember"; //记住我
  static String strLoginUserNameKey = "strLoginUserNameKey"; //登录用户名
  static String strLoginPwdKey = "strLoginPwdKey"; //登录密码

  static const String wtAutoAck = "wtAutoAck"; //测试
  static String wtuser =
      "${SharedPrefUtil().getData(strCartListKey)}wtuser"; //测试
}
